package dao;

import bean.OrderBean;
import bean.UserBean;
import tools.UtilJDBC;

import java.sql.*;
import java.util.ArrayList;

/**
 * @Author 王志康
 * @Date 2021/9/6 19:52
 * @Version 1.0.0
 */
public class OrderDao {
    /**
     * 添加新的订单
     *
     * @param order 待添加的订单
     */
    public static void addOrder(OrderBean order) {
        Connection connection = UtilJDBC.connection;
        String sql = "insert into `order` " +
                "(order_number, order_content, order_time, order_integral)" +
                "values(?,?,?,?)";
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, order.getUserNumber());
            statement.setString(2, order.getOrderContent());
            statement.setDate(3, new Date(order.getOrderTime().getTime()));
            statement.setInt(4, order.getGetIntegral());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除订单
     *
     * @param order 待删除的订单
     */
    public static void deleteOrder(OrderBean order) {
        Connection connection = UtilJDBC.connection;
        String sql = "delete from `order` where order_id=?";
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, order.getId());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有订单信息
     *
     * @return 包含所有订单信息的arraylist
     */
    public static ArrayList<OrderBean> getUserList() {
        Connection connection = UtilJDBC.connection;
        ArrayList<OrderBean> list = new ArrayList<>();
        String sql = "select order_id, order_number, order_content, order_time, order_integral " +
                "from `order`";
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                list.add(new OrderBean(
                        resultSet.getInt("order_id"),
                        resultSet.getString("order_number"),
                        resultSet.getString("order_content"),
                        resultSet.getDate("order_time"),
                        resultSet.getInt("order_integral")
                ));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
